package com.yisu.expressway.driver_revelation.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUnderstander;
import com.iflytek.cloud.SpeechUnderstanderListener;
import com.iflytek.cloud.UnderstanderResult;
import com.kogitune.activity_transition.ActivityTransition;
import com.kogitune.activity_transition.ActivityTransitionLauncher;
import com.kogitune.activity_transition.ExitActivityTransition;

import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.application.ExApplication;
import com.yisu.expressway.customService.adapter.VoiceAssistantAdapter;
import com.yisu.expressway.databinding.ActivityRevelationRoomBinding;
import com.yisu.expressway.databinding.LiveItemImgBinding;
import com.yisu.expressway.databinding.LiveItemTextBinding;
import com.yisu.expressway.databinding.LiveItemVoiceBinding;
import com.yisu.expressway.databinding.RevelationTopicListItemBinding;
import com.yisu.expressway.driver_revelation.model.LiveListItemObj;
import com.yisu.expressway.driver_revelation.model.LiveListObj;
import com.yisu.expressway.driver_revelation.model.TopicListItem;
import com.yisu.expressway.driver_revelation.model.TopicListObj;
import com.yisu.expressway.listener.onClickHandler;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.model.ImageObj;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.widget.DownUpPopupWindow;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.OnRecyclerItemClickListener;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.recyclerview.SampleRecyclerViewAdapter;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.AnimationUtils;
import com.yisu.expressway.utils.BitmapUtil;
import com.yisu.expressway.utils.DisplayUtil;
import com.yisu.expressway.utils.QiniuUploadManager;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RevelationRoomActivity extends BaseActivity implements SuperSwipeRefreshLayout.OnPullRefreshListener,
            PagingRecyclerView.CustomItemTypeActionListener,TextView.OnEditorActionListener,
                AndroidImagePicker.OnImagePickCompleteListener, SpeechUnderstanderListener{

    private ActivityRevelationRoomBinding binding;
    private final static String ROOM_INFO = "room_info";

    LiveListObj roomInfo;

    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;

    SampleRecyclerViewAdapter mAdapter;
    private String currentAddress;
    private LocationInfo locInfo;

    private final static String DEFAULT_VALUE = "0";
    private static final int PHOTO_REQUEST_CAMERA = 200;// 拍照
    private DownUpPopupWindow mDownUpPopupWindow;

    private SpeechUnderstander mSpeechUnderstander;
    private final static String QUESTION_VOICE_PATH = Environment.getExternalStorageDirectory()+"/msc/liveContent.wav";
    private final static String ORIGIN_IMG = "origin_img";

    private final String START_TIME_OUT_INTERVAL = "3000";
    private final String END_SPEAK_TIME_OUT = "1000";
    private final int USER_NO_SPEAK_ERROR = 10118;
    private final int VOICE_RECORD_MAX_LENGTH = 60 * 1000;
    private long startTimeMill;
    private String mVoiceContentLength;
    private MediaPlayer mediaPlayer;
    private AnimationDrawable mVoicePlayAnim;
    CountDownTimer voiceRecordTimer;

    private ExitActivityTransition exitTransition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        binding = DataBindingUtil.setContentView(this,R.layout.activity_revelation_room);
        binding.activityRevelationRoom.setBackgroundColor(getResources().getColor(R.color.color_bg_default));
        initView(getIntent(),savedInstanceState);
    }

    public static void launch(Activity callActivity, LiveListObj roomObj, ImageView originView){

        Intent intent = new Intent(callActivity,RevelationRoomActivity.class);
        intent.putExtra(ROOM_INFO,roomObj);

        Drawable drawable = originView.getDrawable();
        if(drawable != null) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            intent.putExtra(ORIGIN_IMG, bd.getBitmap());
        }

        ActivityTransitionLauncher
                .with(callActivity)
                .from(originView)
                .launch(intent);
    }

    private void initView(Intent intent,Bundle savedInstanceState){
        mTitleBar.transparentBg();
        mTitleBar.setClickBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        roomInfo = (LiveListObj)intent.getSerializableExtra(ROOM_INFO);
        if(roomInfo == null){
            return;
        }

        getCurrentLocation();

        Bitmap originBitmap =  intent.getParcelableExtra(ORIGIN_IMG);
        Drawable originDrawable = null;
        if(originBitmap != null){
            originDrawable = new BitmapDrawable(originBitmap);
        }

        if(originDrawable == null){
            originDrawable = getResources().getDrawable(R.drawable.ic_default_home_banner);
        }

//        ImageObj imageObj = new ImageObj();
//        imageObj.setImageUrl(roomInfo.getImage());
//        imageObj.setDefaultDrawable(originDrawable);
//        binding.setImageItem(imageObj);
        Glide.with(this)
                .load(roomInfo.getImage())
                .asBitmap()
                .placeholder(originDrawable)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .animate(R.anim.fade_in_image)
                .into(binding.ivCover);

        int statusStrId = roomInfo.getStatus() == 1 ? R.string.live_status_ongoing : R.string.live_status_idle;
        binding.setLiveStatus(getResources().getString(statusStrId));
        binding.setLiveCount(String.valueOf(roomInfo.getJoinNum()) + getResources().getString(R.string.join_peopel_unit));

        binding.refreshLayout.setOnPullRefreshListener(this);
        binding.refreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        binding.refreshLayout.setHeaderView(createHeaderView());
        binding.refreshLayout.setTargetScrollWithLayout(true);
        binding.rvContent.setLayoutManager(new LinearLayoutManager(this));
        binding.rvContent.addItemDecoration(new DividerListItemDecoration(this,LinearLayoutManager.VERTICAL,4));

//        showLoading();
        binding.rvContent.init(this,20);
        mAdapter = binding.rvContent.getDataAdapter();
        binding.edtTextInput.setOnEditorActionListener(this);
        initVoiceParams();
        mediaPlayer = new MediaPlayer();
        initItemLongClick();

        if(roomInfo.getIsPersonal() == 1){
            switchUnreadMsgRecord(false);
        }

        exitTransition = ActivityTransition
                .with(intent)
                .to(binding.ivCover)
                .enterListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        startAlphaAnimation(true);
                    }

                    @Override
                    public void onAnimationStart(Animator animation) {

                    }
                })
                .start(savedInstanceState);
        binding.inputRoot.setVisibility( roomInfo.getStatus() == 1 ? View.VISIBLE : View.GONE);

    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(this)
                .inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initItemLongClick(){
        binding.rvContent.addOnItemTouchListener(new OnRecyclerItemClickListener(binding.rvContent) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder) {

            }

            @Override
            public void onItemLOngClick(final RecyclerView.ViewHolder viewHolder) {
                int pos = viewHolder.getAdapterPosition();
                final TopicListItem item = (TopicListItem)mAdapter.getItem(pos);
                String userAccount = LoginManager.getUserAccount();
                if(!StringUtil.isNullOrEmpty(userAccount) && item.getUserAccount().equals(userAccount)){
                    final MultiButtonDialog multiButtonDialog = new MultiButtonDialog(RevelationRoomActivity.this);
                    multiButtonDialog.show();
                    multiButtonDialog.setContentText(R.string.delete_content_notify);
                    multiButtonDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
                        @Override
                        public void onPositiveClick(String inputContent) {
                            multiButtonDialog.dismiss();
                            doDeleteContent(item.getRecordId());
                        }
                    });
                }
            }
        });
    }

    public void onChooseImg(View itemView){
        if (mDownUpPopupWindow == null) {
            View view = getLayoutInflater().inflate(R.layout.popwindow_down_up_pic_select, null);
            mDownUpPopupWindow = new DownUpPopupWindow(this, view);
            view.findViewById(R.id.tv_photograph).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pickPicFromCamera();
                    dismissPopDlg();
                }
            });
            view.findViewById(R.id.tv_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pickPicFromAlbum();
                    dismissPopDlg();
                }
            });
            view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissPopDlg();
                }
            });
        }
        mDownUpPopupWindow.showAtLocation(mTitleBar, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                0);
    }

    public void onVoiceRecord(View view){
        int ret;
        if(mSpeechUnderstander.isUnderstanding()){// 开始前检查状态
            mSpeechUnderstander.stopUnderstanding();

        }else {
            ret = mSpeechUnderstander.startUnderstanding(this);
            if(ret != 0){
                ToastUtil.displayShortToastMsg(this,"语义理解失败,错误码:"	+ ret);
            }else {
                showVoiceLine(true);
            }
        }
    }

    private void showVoiceLine(boolean isShow){
        AnimationUtils.startVoiceLineAnimation(isShow,binding.voiceLine,binding.inputParent);
    }

    private void initVoiceParams(){
        mSpeechUnderstander = SpeechUnderstander.createUnderstander(this, mSpeechUdrInitListener);
        mSpeechUnderstander.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mSpeechUnderstander.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mSpeechUnderstander.setParameter(SpeechConstant.VAD_BOS, START_TIME_OUT_INTERVAL);
        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mSpeechUnderstander.setParameter(SpeechConstant.VAD_EOS, END_SPEAK_TIME_OUT);

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mSpeechUnderstander.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mSpeechUnderstander.setParameter(SpeechConstant.ASR_AUDIO_PATH, QUESTION_VOICE_PATH);
    }

    /**
     * 初始化监听器（语音到语义）。
     */
    private InitListener mSpeechUdrInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {

            }
        }
    };

    @Override
    public void onRefresh() {
        if(mAnimation != null) {
            mAnimation.start();
        }
        binding.rvContent.refreshData();
    }

    @Override
    public void onPullDistance(int distance) {
        int index = distance / 25;

        int resId = R.drawable.car_1;
        switch (index){
            case 2:
                resId = R.drawable.car_2;
                break;
            case 3:
                resId = R.drawable.car_3;
                break;
            case 4:
                resId = R.drawable.car_4;
                break;
            case 5:
                resId = R.drawable.car_5;
                break;
            case 6:
                resId = R.drawable.car_6;
                break;
            case 7:
                resId = R.drawable.car_7;
                break;
            case 8 :
                resId = R.drawable.car_8;
                break;
            case 9:
                resId = R.drawable.car_9;
                break;
            case 10 :
                resId = R.drawable.car_10;
                break;
        }

        if(!isFreshEnable) {
            carImage.setBackgroundResource(resId);
        }
    }

    @Override
    public void onPullEnable(boolean enable) {
        isFreshEnable = enable;
        if(enable) {
            carImage.setBackgroundResource(R.color.colorTransparent);
            carImage.setImageResource(R.drawable.car_frame);
            mAnimation = (AnimationDrawable) carImage.getDrawable();
        }
    }

    @Override
    public void fetchData(int start, int pageSize) {
        getLiveList(start,pageSize);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView;
        switch (viewType){
            case TopicListItem.LIVE_TYPE_TEXT:
                itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.live_item_text, parent, false);
                return new TextHolder(itemView);
            case TopicListItem.LIVE_TYPE_IMG:
                itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.live_item_img, parent, false);
                return new ImgHoder(itemView);
            case TopicListItem.LIVE_TYPE_VOICE:
                itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.live_item_voice, parent, false);
                return new VoiceHolder(itemView);
        }
        return null;
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder holder, int position, Object item) {
        if(holder instanceof VoiceHolder){
            ((VoiceHolder) holder).bind((TopicListItem)item);
        }else if(holder instanceof TextHolder){
            ((TextHolder) holder).bind((TopicListItem)item);
        }else if (holder instanceof ImgHoder){
            ((ImgHoder) holder).bind((TopicListItem)item);
        }
    }

    @Override
    public int getDataItemType(int position) {
        ArrayList<TopicListItem> mData = mAdapter.getData();
        if(mData == null || position >= mData.size()){
            return 0;
        }else {
            return mData.get(position).getContentType();
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_SEND){
            String content = binding.edtTextInput.getText().toString();
            if(!StringUtil.isNullOrEmpty(content)){
                sendContent2Server(content,DEFAULT_VALUE,TopicListItem.LIVE_TYPE_TEXT);
            }

        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTO_REQUEST_CAMERA:
                String currentPhotoPath = AndroidImagePicker.getInstance().getCurrentPhotoPath();
                uploadImg2Qiniu(currentPhotoPath,DEFAULT_VALUE,TopicListItem.LIVE_TYPE_IMG);
                break;
            default:
                break;
        }
    }

    @Override
    public void onImagePickComplete(List<ImageItem> items) {
        if(items != null && items.size() > 0){
            uploadImg2Qiniu(items.get(0).path,DEFAULT_VALUE,TopicListItem.LIVE_TYPE_IMG);
        }
    }

    /**
     * 用户点击声音波形主动停止语音输入
     * @param view
     */
    public void onStopVoiceRecord(View view){
        if(mSpeechUnderstander.isUnderstanding()){// 开始前检查状态
            onEndOfSpeech();
            mSpeechUnderstander.stopUnderstanding();
        }
    }

    private void startTimeCountDown(){
        if(voiceRecordTimer == null) {
            voiceRecordTimer = new CountDownTimer(VOICE_RECORD_MAX_LENGTH, VOICE_RECORD_MAX_LENGTH) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    onStopVoiceRecord(null);
                }
            };
        }

        voiceRecordTimer.start();
    }


    @Override
    public void onVolumeChanged(int volume, byte[] bytes) {
        binding.voiceLine.setVolume(volume);
    }

    @Override
    public void onBeginOfSpeech() {
        startTimeMill = System.currentTimeMillis();
        startTimeCountDown();
    }

    @Override
    public void onEndOfSpeech() {
        showVoiceLine(false);
        long interVal = (System.currentTimeMillis() - startTimeMill) / 1000;
        mVoiceContentLength = String.valueOf(interVal) + "''";
        if(voiceRecordTimer  != null){
            voiceRecordTimer.cancel();
        }
    }

    @Override
    public void onResult(UnderstanderResult understanderResult) {
        uploadImg2Qiniu(QUESTION_VOICE_PATH,mVoiceContentLength,TopicListItem.LIVE_TYPE_VOICE);
    }

    @Override
    public void onError(SpeechError speechError) {
        if(speechError.getErrorCode() == USER_NO_SPEAK_ERROR){

        }
    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {

    }


    public  class VoiceHolder extends BaseRvAdapter.SampleViewHolder implements onClickHandler {

        private LiveItemVoiceBinding itemBinding;

        public VoiceHolder(View view){
            super(view);
            itemBinding = DataBindingUtil.bind(view);
        }

        public void bind(@NonNull TopicListItem listItem){
            itemBinding.setTopicItem(listItem);
            itemBinding.setClickListener(this);
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(listItem.getAvatarUrl())
                    .asBitmap()
                    .placeholder(R.drawable.ic_customer_service_header)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .animate(R.anim.fade_in_image)
                    .into(itemBinding.ivAvatar);
        }

        @Override
        public void handleClick(View view) {
            playVoice(itemBinding.getTopicItem().getContent(),itemBinding.ivVoiceIcon);
        }
    }

    public  class TextHolder extends BaseRvAdapter.SampleViewHolder{

        private LiveItemTextBinding itemBinding;

        public TextHolder(View view){
            super(view);
            itemBinding = DataBindingUtil.bind(view);
        }

        public void bind(@NonNull TopicListItem listItem){
            itemBinding.setTopicItem(listItem);
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(listItem.getAvatarUrl())
                    .asBitmap()
                    .placeholder(R.drawable.ic_customer_service_header)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .animate(R.anim.fade_in_image)
                    .into(itemBinding.ivAvatar);
        }
    }

    public  class ImgHoder extends BaseRvAdapter.SampleViewHolder implements onClickHandler{

        private LiveItemImgBinding itemBinding;

        public ImgHoder(View view){
            super(view);
            itemBinding = DataBindingUtil.bind(view);
        }

        public void bind(@NonNull TopicListItem listItem){
            itemBinding.setTopicItem(listItem);
            itemBinding.setClickListener(this);
            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(listItem.getAvatarUrl())
                    .asBitmap()
                    .placeholder(R.drawable.ic_customer_service_header)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .animate(R.anim.fade_in_image)
                    .into(itemBinding.ivAvatar);

            Glide.with(ExApplication.getInstance().getApplicationContext())
                    .load(listItem.getContent())
                    .asBitmap()
                    .placeholder(R.drawable.ic_default_home_banner)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .animate(R.anim.fade_in_image)
                    .into(itemBinding.ivCover);
        }

        @Override
        public void handleClick(View view) {
            TopicListItem selectItem = itemBinding.getTopicItem();
            ImgViewActivity.launch(RevelationRoomActivity.this,selectItem.getContent(),view);
        }
    }

    /**
     * 将语音或者图片 先上传至七牛云
     * @param contentUrl 多媒体本地url
     * @param contentLength 语音内容长度
     * @param type 多媒体类型
     */
    private void uploadImg2Qiniu(String contentUrl,final String contentLength,final int type){
        String filePath;

        if(type == TopicListItem.LIVE_TYPE_IMG) {
            filePath = BitmapUtil.compressBitmap(contentUrl);//压缩图片
            if (StringUtil.isNullOrEmpty(filePath)) {
                filePath = contentUrl;
            }
        }else {
            filePath = contentUrl;
        }

        QiniuUploadManager.getInstance().getTokenAndUpload(filePath,type,new QiniuUploadManager.UpLoadListener() {
            @Override
            public void uploadSuccess(String url, int w, int h) {
                sendContent2Server(url,contentLength,type);
            }

            @Override
            public void uploadFail(String error) {
                ToastUtil.displayShortToastMsg(TextUtils.isEmpty(error) ? "上传失败" : error);
            }

            @Override
            public void onGetToken(String token) {

            }

            @Override
            public void onGetTokenApiFail(String error) {
                ToastUtil.displayShortToastMsg(error);
            }

            @Override
            public void onGetTokenNetworkFail(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg("网络不给力");
            }
        });
    }

    public void dismissPopDlg() {
        if (mDownUpPopupWindow != null && mDownUpPopupWindow.isShowing()) {
            mDownUpPopupWindow.dismiss();
            mDownUpPopupWindow = null;
        }
    }

    private void pickPicFromAlbum() {
        AndroidImagePicker.getInstance().pickSingle(this,false,this);
    }

    private void pickPicFromCamera() {
        try {
            AndroidImagePicker.getInstance().takePicture(this, PHOTO_REQUEST_CAMERA);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRefreshAnimation(){
        if(mAnimation != null && mAnimation.isRunning()) {
            binding.refreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }
    }

    @Override
    public void onBackPressed(){
        if(roomInfo != null && roomInfo.getIsPersonal() == 1){
            switchUnreadMsgRecord(true);
        }else {
            doExitAnimation();
        }
    }

    private void getLiveList(final int offset, int limit){
        int pageNumber = offset / limit + 1;

        Map<String, Object> params = new HashMap();
        params.put("pageindex",pageNumber);
        params.put("pagesize",limit);
        params.put("roomNo",roomInfo.getRoomNo());

        ApiClientHelper.postApi(ApiSetting.getLiveItemList(), new TypeToken<TopicListObj>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<TopicListObj>>() {
            @Override
            public void onResponse(ApiResult<TopicListObj> result) {

                if(offset == 0) {
                    stopRefreshAnimation();
                    dismissLoading();
                }


                if (!result.success) {
                    ToastUtil.displayShortToastMsg(result.getMsg());
                    binding.rvContent.dataFetchDone(null);
                    return;
                }

                TopicListObj itemObj = result.getResult();
                if(itemObj != null){
                    binding.rvContent.dataFetchDone(itemObj.getRidersBrokeNewsDetailVos());
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(volleyError.getMessage());
                binding.rvContent.dataFetchDone(null);
                dismissLoading();
                stopRefreshAnimation();
            }
        }, this);
    }

    /**
     * 发送爆料内容
     * @param content 内容 文本 or 语音 or 图片的url
     * @param contentLength 内容长度，语音内容有效。其它类型为0
     * @param type 内容类型
     */
    private void sendContent2Server(String content, String contentLength, final int type){

        ToastUtil.displayShortToastMsg(R.string.publish_is_ongoing);

        Map<String, Object> params = new HashMap();

        params.put("address",currentAddress);
        params.put("content",content);
        params.put("contentLength",contentLength);
        params.put("contentType",type);
        String latitude = locInfo == null ? DEFAULT_VALUE : String.valueOf(locInfo.getLatitude());
        String lotitude = locInfo == null ? DEFAULT_VALUE : String.valueOf(locInfo.getLongitude());
        params.put("latitude",latitude);
        params.put("longitude",lotitude);
        params.put("roomNo",roomInfo.getRoomNo());


        ApiClientHelper.postApi(ApiSetting.sendLiveContent(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {

                if (!result.success) {
                    ToastUtil.displayShortToastMsg(result.getMsg());
                    return;
                }

                binding.rvContent.refreshData();
                ToastUtil.displayShortToastMsg(R.string.publish_success);
                if(type == TopicListItem.LIVE_TYPE_TEXT){
                    binding.edtTextInput.setText("");
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(volleyError.getMessage());
            }
        }, this);
    }

    private void getCurrentLocation(){
        LocationService.getInstance().start(new LocationListener() {
            @Override
            public void onSuccess(LocationInfo info) {
                currentAddress = info.getStreet();
                locInfo = info;
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                currentAddress = getResources().getString(R.string.default_no_address);
            }
        });
    }

    /**
     * 播放语音内容
     * @param url 语音url
     * @param imageView 语音播放时动画对象
     */
    private void playVoice(String url,ImageView imageView){
        if(mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
        }
        try {
            if(mediaPlayer.isPlaying()) {
                stopVoicePlayAnimation();
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
                mediaPlayer = new MediaPlayer();
            }
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
            startVoicePlayAnimation(imageView);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayer.release();
                    mediaPlayer = null;
                    stopVoicePlayAnimation();
                }
            });

        } catch (IOException e) {

        }
    }

    private void startVoicePlayAnimation(ImageView view){
        mVoicePlayAnim = (AnimationDrawable) view.getDrawable();
        mVoicePlayAnim.start();
    }

    private void stopVoicePlayAnimation(){
        if(mVoicePlayAnim != null) {
            mVoicePlayAnim.selectDrawable(0);
            mVoicePlayAnim.stop();
        }
    }

    /**
     * 删除自己发的内容
     * @param recordId 内容ID
     */
    private void doDeleteContent(int recordId){

        Map<String, Object> params = new HashMap();
        params.put("recordId",recordId);

        ToastUtil.displayShortToastMsg(R.string.delete_is_ongoing);
        ApiClientHelper.postApi(ApiSetting.deleteSelectContent(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {

                if (!result.success) {
                    ToastUtil.displayShortToastMsg(result.getMsg());
                    return;
                }

                binding.rvContent.refreshData();
                ToastUtil.displayShortToastMsg(R.string.do_action_success);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(volleyError.getMessage());
            }
        }, this);
    }

    /**
     * 如果是自己的直播间，进入时关闭未读消息统计，退出时打开未读消息统计
     * @param isOn 打开关闭
     */
    private void switchUnreadMsgRecord(final boolean isOn){

        Map<String, Object> params = new HashMap();
        params.put("roomNo",roomInfo.getRoomNo());
        params.put("switchStatus",isOn ? 1 : 0);

        ApiClientHelper.postApi(ApiSetting.switchUnReadMsgRecord(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {

                if(isOn){
                    doExitAnimation();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                if(isOn){
                    doExitAnimation();
                }
                ToastUtil.displayShortToastMsg(volleyError.getMessage());
            }
        }, this);
    }

    private void doExitAnimation(){
        startAlphaAnimation(false);
        exitTransition.exit(RevelationRoomActivity.this);
    }

    /**
     * activty启动/退出 布局动画
     * @param show 是否显示布局
     */
    private void startAlphaAnimation(boolean show){

        int duration = show ? 300 : 10;
        float startL = show ? 0.0f : 1.0f ;
        float endL = show ? 1.0f : 0.0f ;

        float startY = show ? 100.0f : 0.0f;
        float endY = show ? 0.0f : 100.0f;

        PropertyValuesHolder alphaAnim = PropertyValuesHolder.ofFloat("alpha", startL,
                endL);
        PropertyValuesHolder transYAnim = PropertyValuesHolder.ofFloat("translationY", startY,
                endY);

        ObjectAnimator.ofPropertyValuesHolder(binding.statusRoot,alphaAnim,transYAnim).setDuration(duration).start();
        ObjectAnimator.ofPropertyValuesHolder(binding.refreshLayout,alphaAnim,transYAnim).setDuration(duration).start();
        ObjectAnimator.ofPropertyValuesHolder(binding.inputRoot,alphaAnim,transYAnim).setDuration(duration).start();

        if(!show) {
            binding.titlebar.setVisibility(View.GONE);
            binding.activityRevelationRoom.setBackgroundColor(Color.TRANSPARENT);
        }

    }

}
